package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDataVo;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
/**
 * 设备管理Service业务层处理
 * 
 * @author ruoyi
 *
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper,Device> implements IDeviceService {

    private final DeviceMapper deviceMapper;
    private final IoTDAClient client;
    private final RedisTemplate<String,String> redisTemplate;
    public DeviceServiceImpl(DeviceMapper deviceMapper,IoTDAClient client,RedisTemplate<String,String> redisTemplate){
        this.deviceMapper = deviceMapper;
        this.client = client;
        this.redisTemplate = redisTemplate;
    }



    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    @Override
    public void syncProductList() {
        ListProductsRequest request = new ListProductsRequest();
        request.setLimit(50);
        ListProductsResponse response = client.listProducts(request);
        if(response.getHttpStatusCode()!=200){
            throw new BaseException("产品同步失败");
        }
        List<ProductSummary> products = response.getProducts();
        redisTemplate.boundValueOps(CacheConstants.IOT_ALL_PRODUCT_LIST).set(JSONUtil.toJsonStr(products));
    }

    @Override
    public List<ProductVo> allProduct() {
        String string = redisTemplate.boundValueOps(CacheConstants.IOT_ALL_PRODUCT_LIST).get();
        return JSONUtil.toList(string, ProductVo.class);
    }

    @Override
    public void register(DeviceDto dto) {

        //判断设备名称是否重复
        LambdaQueryWrapper<Device> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Device::getDeviceName,dto.getDeviceName());
        Device one = this.getOne(queryWrapper1);
        if(one!=null){
            throw new BaseException("设备名称不能重复");
        }
        //判断设备标识是否重复
        LambdaQueryWrapper<Device> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(Device::getNodeId,dto.getNodeId());
        Device two = this.getOne(queryWrapper2);
        if(two!=null){
            throw new BaseException("设备标识不能重复");
        }
        //判断同一位置是否有同一设备
        LambdaQueryWrapper<Device> queryWrapper3 = new LambdaQueryWrapper<>();
        queryWrapper3.eq(Device::getRemark,dto.getRemark());
        queryWrapper3.eq(Device::getProductKey,dto.getProductKey());
        Device three = this.getOne(queryWrapper3);
        if(three!=null){
            throw new BaseException("同一位置不可以有同一设备");
        }

        //数据库中有iotid，所以先保存IOT平台
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        //设备标识码
        body.setNodeId(dto.getNodeId());
        body.setDeviceName(dto.getDeviceName());
        body.setProductId(dto.getProductKey());

        AuthInfo authInfo = new AuthInfo();
        //密钥，32位，自己生成
        String string = RandomUtil.randomString(32);
        authInfo.setSecret(string);
        body.setAuthInfo(authInfo);
        body.setDescription(dto.getDeviceDescription());

        request.setBody(body);
        AddDeviceResponse response = client.addDevice(request);
        //请求已被实现，只有在新增的时候会返回201
        if(response.getHttpStatusCode()!=201){
            throw new BaseException("IOT注册设备失败");
        }

        Device device = createDevice(response,string,dto);
        this.save(device);

    }
    //保存本地数据
    private  Device createDevice(AddDeviceResponse response,String string,DeviceDto dto){
        Device device = new Device();
        device.setIotId(response.getDeviceId());
        device.setSecret(string);
        //拼接字符串
        device.setBindingLocation(dto.getBindingLocation()+"");
        device.setLocationType(dto.getLocationType());
        device.setPhysicalLocationType(dto.getPhysicalLocationType());
        device.setDeviceName(dto.getDeviceName());
        device.setProductKey(dto.getProductKey());
        device.setProductName(dto.getProductName());
        device.setDeviceDescription(dto.getDeviceDescription());
        device.setNodeId(dto.getNodeId());
        device.setRemark(dto.getRemark());
        return device;
    }

    @Override
    public DeviceDetailVo viewDeviceDetails(String iotId) {
        //先查询自己的表
        LambdaQueryWrapper<Device> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Device::getIotId,iotId);
        Device one = this.getOne(lambdaQueryWrapper);
        if (one==null) {
            throw new BaseException("参数有误");
        }
        //使用hutool的toBean方法，直接将一个对象转成另一个类型的对象
        DeviceDetailVo detailVo = BeanUtil.toBean(one, DeviceDetailVo.class);
        //再查询IOT
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);
        if(response.getHttpStatusCode()!=200){
            throw new BaseException("IOT查询失败");
        }
        String activeTimeStr = response.getActiveTime();
        // 把字符串转成LocalDateTime
        LocalDateTime parse = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
        // DateTimeZoneConverter是今天资料中提供的一个工具类
        LocalDateTime activeTime = DateTimeZoneConverter.utcToShanghai(parse);
        detailVo.setActiveTime(activeTime);
        //设备状态
        detailVo.setDeviceStatus(response.getStatus());
        return detailVo;
    }

    @Override
    public List<DeviceDataVo> queryServiceProperties(String iotId) {
        //准备返回数据的接收
        List<DeviceDataVo> list = new ArrayList<>();

        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        //根据id查找
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        //判断返回的状态码
        if(response.getHttpStatusCode()!=200){
            throw new BaseException("IOT设备查询失败");
        }
        //打断点
        List<DeviceShadowData> shadow = response.getShadow();
        DeviceShadowData deviceShadowData = shadow.get(0);
        DeviceShadowProperties reported = deviceShadowData.getReported();

        String time = reported.getEventTime();

        LocalDateTime eventTimeUtc = LocalDateTimeUtil.parse(time, "yyyyMMdd'T'HHmmss'Z'");
        //转为上海
        LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(eventTimeUtc);

        Object properties = reported.getProperties();
        JSONObject jsonObject = JSONUtil.parseObj(properties);
        jsonObject.forEach(( key, value ) -> {
            DeviceDataVo deviceDataVo = new DeviceDataVo();
            deviceDataVo.setFunctionId(key);
            deviceDataVo.setEventTime(eventTime);
            deviceDataVo.setValue(value);
            list.add(deviceDataVo);
        });

        return list;
    }

    @Override
    public void updateDevice(DeviceDto dto) {
        //判断设备名称是否重复
        LambdaQueryWrapper<Device> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Device::getDeviceName,dto.getDeviceName());
        queryWrapper1.ne(dto.getId() != null, Device::getId, dto.getId());
        Device one = this.getOne(queryWrapper1);
        if(one!=null){

            throw new BaseException("设备名称不能重复");
        }
        //判断同一位置是否有同一设备
        LambdaQueryWrapper<Device> queryWrapper3 = new LambdaQueryWrapper<>();
        queryWrapper3.eq(Device::getRemark,dto.getRemark());
        queryWrapper3.eq(Device::getProductKey,dto.getProductKey());
        queryWrapper3.ne(dto.getId() != null, Device::getId, dto.getId());
        Device three = this.getOne(queryWrapper3);
        if(three!=null){
            throw new BaseException("同一位置不可以有同一设备");
        }

        //创建了一个 更新设备请求对象
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        //设备id
        request.withDeviceId(dto.getIotId());
        //更新的对象
        UpdateDevice body = new UpdateDevice();
        //创建了一个 不包含密钥的认证信息对象 并设置了安全访问属性
        AuthInfoWithoutSecret authInfobody = new AuthInfoWithoutSecret();
        authInfobody.withSecureAccess(true);
        //将认证信息对象 设置到 请求主体 中
        body.withAuthInfo(authInfobody);
        //iot平台更新自带字段
        body.withDescription(dto.getDeviceDescription());
        body.withDeviceName(dto.getDeviceName());
        //某个对象设置扩展信息
        // 设置设备扩展信息
        Map<String, Object> extension = new HashMap<>();
        extension.put("physicalLocationType", dto.getPhysicalLocationType());
        extension.put("locationType", dto.getLocationType());
        extension.put("bindingLocation", dto.getBindingLocation());
        extension.put("remark", dto.getRemark());
        extension.put("nodeId", dto.getNodeId());
        extension.put("productKey", dto.getProductKey());
        extension.put("productName", dto.getProductName());
        String escapedJson2 =JSONUtil.toJsonStr(extension).replace("\"", "\\\"");
        body.withExtensionInfo(escapedJson2);
        //是将请求体对象设置到主请求对象中
        request.withBody(body);
        UpdateDeviceResponse response = client.updateDevice(request);
        if(response.getHttpStatusCode()!=200){
            throw new BaseException("IOT修改设备失败");
        }
        LambdaUpdateWrapper<Device> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Device::getId,dto.getId());
        updateWrapper.set(Device::getDeviceName,dto.getDeviceName());
        updateWrapper.set(Device::getRemark,dto.getRemark());
        this.update(updateWrapper);

    }

    @Override
    public void deleteDevice(String iotId) {
        //创建了一个删除设备请求对象
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        DeleteDeviceResponse response = client.deleteDevice(request);
        //IOT设备删除返回码是204
        if(response.getHttpStatusCode()!=204){
            throw new BaseException("IOT设备删除失败");
        }
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getIotId,iotId);
        this.remove(queryWrapper);
    }

    @Override
    public AjaxResult queryProductById(String productKey) {
        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse response = client.showProduct(request);
        if(response.getHttpStatusCode()!=200){
            throw new BaseException("IOT产品查询");
        }
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        return AjaxResult.success(serviceCapabilities);
    }
}
